package xyz.zhouzhaodong.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.zhouzhaodong.crm.dto.StaffDto;
import xyz.zhouzhaodong.crm.entity.Staff;
import xyz.zhouzhaodong.crm.entity.Station;
import xyz.zhouzhaodong.crm.mapper.StaffMapper;
import xyz.zhouzhaodong.crm.mapper.StationMapper;
import xyz.zhouzhaodong.crm.service.StaffService;
import xyz.zhouzhaodong.crm.util.EncryptionDecryptionUtil;
import xyz.zhouzhaodong.crm.util.ExceptionEnum;
import xyz.zhouzhaodong.crm.util.RestMessage;
import xyz.zhouzhaodong.crm.util.TokenUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.util.*;

/**
 * 员工操作
 *
 * @author zhouzhaodong
 */
@Service
public class StaffServiceImpl implements StaffService {

    private static final Logger logger = LoggerFactory.getLogger(StaffServiceImpl.class);

    @Resource
    StaffMapper staffMapper;

    @Override
    public RestMessage login(String userName, String password) {

        // 查询数据库判断是否登录成功
        if (userName == null || "".equals(userName) || password == null || "".equals(password)) {
            return RestMessage.failed("");
        }
        // 加密密码
        password = EncryptionDecryptionUtil.aesEncode(password);
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.eq("name", userName);
        wrapper.eq("password", password);
        wrapper.eq("flag", 0);
        Staff staff = staffMapper.selectOne(wrapper);
        if (staff == null) {
            return new RestMessage(ExceptionEnum.LOGIN_ERROR_USER.getCode(), ExceptionEnum.LOGIN_ERROR_USER.getMsg());
        }
        String token = TokenUtil.sign(staff);
        logger.info("登录用户为:" + userName + ",token为:" + token);
        // 根据用户获取部门和岗位信息
        StaffDto staffDto = staffMapper.selectStaffMessage(staff.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("staffId", staff.getId());
        map.put("stationId", staff.getStationId());
        map.put("stationName", staffDto.getStationName());
        map.put("departmentId", staffDto.getDepartmentId());
        map.put("departmentName", staffDto.getDepartmentName());
        return RestMessage.success(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage register(String userName, String password) {
        try {
            // 首先需要查询是否有重复的用户名
            QueryWrapper<Staff> wrapper = new QueryWrapper<>();
            wrapper.eq("name", userName);
            wrapper.eq("flag", 0);
            List<Staff> list = staffMapper.selectList(wrapper);
            if (list != null && list.size() > 0) {
                return new RestMessage(ExceptionEnum.REGISTER_ERROR.getCode(), ExceptionEnum.REGISTER_ERROR.getMsg());
            }
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            // 加密密码
            password = EncryptionDecryptionUtil.aesEncode(password);
            Staff staff = new Staff();
            staff.setId(id);
            staff.setName(userName);
            staff.setPassword(password);
            staff.setCreateUser(id);
            staff.setCreateTime(new Date());
            staffMapper.insert(staff);
            return RestMessage.success(userName);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage changePassword(String id, String passwordOld, String passwordNew) {
        try {
            // 首先确认原密码是否正确
            // 加密密码
            passwordOld = EncryptionDecryptionUtil.aesEncode(passwordOld);
            passwordNew = EncryptionDecryptionUtil.aesEncode(passwordNew);
            Staff staff = staffMapper.selectById(id);
            if (staff.getFlag() == 1) {
                return new RestMessage(ExceptionEnum.USER_FLAG.getCode(), ExceptionEnum.USER_FLAG.getMsg());
            }
            if (!staff.getPassword().equals(passwordOld)) {
                return new RestMessage(ExceptionEnum.USER_PASSWORD.getCode(), ExceptionEnum.USER_PASSWORD.getMsg());
            }
            Staff changePassword = new Staff();
            changePassword.setId(id);
            changePassword.setPassword(passwordNew);
            int num = staffMapper.updateById(changePassword);
            return RestMessage.success(num);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage updateStaff(Staff staff) {
        try {
            // 先判断是否存在该用户
            QueryWrapper<Staff> wrapper = new QueryWrapper<>();
            wrapper.eq("name", staff.getName());
            wrapper.eq("flag", 0);
            List<Staff> list = staffMapper.selectList(wrapper);
            if (list != null && list.size() > 0 && !Objects.equals(staff.getId(), list.get(0).getId())) {
                return new RestMessage(ExceptionEnum.REGISTER_ERROR.getCode(), ExceptionEnum.REGISTER_ERROR.getMsg());
            }
            staff.setUpdateTime(new Date());
            staff.setUpdateUser(staff.getId());
            staffMapper.updateUser(staff);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage deleteStaff(String id, String staffId) {
        try {
            Staff staff = new Staff();
            staff.setId(id);
            staff.setFlag(1);
            staff.setUpdateUser(staffId);
            staff.setUpdateTime(new Date());
            staffMapper.updateById(staff);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    public RestMessage selectOne(String id) {
        // 查询时必须为未删除用户
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("flag", 0);
        Staff staff = staffMapper.selectOne(queryWrapper);
        return RestMessage.success(staff);
    }

    @Override
    public RestMessage selectStaffList(StaffDto staffDto) {
        Page<StaffDto> page = new Page<>(staffDto.getPageNo(),
                staffDto.getPageSize() == 0 ? 10 : staffDto.getPageSize());
        if(staffDto.getFlag() == null){
            staffDto.setFlag(0);
        }
        IPage<StaffDto> list = staffMapper.selectStaffList(staffDto, page);
        return RestMessage.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage addStaff(StaffDto staffDto) {
        try {
            Staff staff = new Staff();
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            staff.setId(id);
            staff.setName(staffDto.getName());
            String password = staffDto.getPassword();
            if (password == null || "".equals(password)) {
                // 不设置默认密码为123456
                password = "123456";
            }
            // 加密密码
            password = EncryptionDecryptionUtil.aesEncode(password);
            staff.setPassword(password);
            // 获取岗位信息
            staff.setStationId(staffDto.getStationId());
            staff.setCreateUser(staffDto.getStaffId());
            staff.setCreateTime(new Date());
            staffMapper.insert(staff);
            return RestMessage.success(id);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage resetPasswrod(StaffDto staffDto) {
        try {
            Staff staff = new Staff();
            staff.setId(staffDto.getId());
            staff.setUpdateUser(staffDto.getStaffId());
            staff.setUpdateTime(new Date());
            // 修改密码
            String password = EncryptionDecryptionUtil.aesEncode(staffDto.getPassword());
            staff.setPassword(password);
            staffMapper.updateById(staff);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage restStation(String id, String staffId, String stationId) {
        try {
            Staff staff = new Staff();
            staff.setId(id);
            staff.setStationId(stationId);
            staff.setUpdateUser(staffId);
            staff.setUpdateTime(new Date());
            staffMapper.updateById(staff);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }
}
